<?php


namespace app\common\service;

use app\common\service\companyIndustry\realtime\NitreEmissionService;
use app\common\service\companyIndustry\realtime\RealtimeEmissionService;
use app\common\service\companyIndustry\realtime\SulfurEmissionService;
use app\common\service\companyIndustry\simulation\SimulationEmissionService;
use app\common\service\companyIndustry\tsinghua\TsinghuaEmissionService;

class ControlEmissionService extends BaseService
{
    /**
     * 根据设施ID获取 - 精准管控 - 减排前7天排放量 - 小时平均值
     * @param int $facilityId 设施ID
     * @param string $planNumber 预案编号
     * @return float|string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-24
     */
    public function getControlEmissionHourAverageByFacilityId($facilityId, $planNumber)
    {
        $company = new CompanyService();
        $type    = $company->getTypeByFacilityId($facilityId);
        $result  = '';
        //脱硝
        if ($type == 1) {
            $nitre  = new NitreEmissionService();
            $result = $nitre->beforeSingleCompanySingleDrainSingleFacilityHourAverage($facilityId, $planNumber);
        }
        //脱硫
        if ($type == 2) {
            $sulfur = new SulfurEmissionService();
            $result = $sulfur->beforeSingleCompanySingleDrainSingleFacilityHourAverage($facilityId, $planNumber);
        }
        return $result;
    }

    /**
     * 根据设施ID获取 - 精准管控 - 减排前7天排放量 - 天平均值
     * @param int $facilityId 设施ID
     * @param string $planNumber 预案编号
     * @param bool $every 是否有每天
     * @return float|string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-24
     */
    public function getControlEmissionDayAverageByFacilityId($facilityId, $planNumber, $every = false)
    {
        $company = new CompanyService();
        $type    = $company->getTypeByFacilityId($facilityId);
        $result  = '';
        //脱硝
        if ($type == 1) {
            $nitre  = new NitreEmissionService();
            $result = $nitre->beforeSingleCompanySingleDrainSingleFacilityDayAverage($facilityId, $planNumber, $every);
        }
        //脱硫
        if ($type == 2) {
            $sulfur = new SulfurEmissionService();
            $result = $sulfur->beforeSingleCompanySingleDrainSingleFacilityDayAverage($facilityId, $planNumber, $every);
        }
        return $result;
    }


    /**
     * 根据设施ID获取 - 精准管控 - 减排前7天排放量 - 7天总和
     * @param int $facilityId 设施ID
     * @param string $planNumber 预案编号
     * @return float|string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-24
     */
    public function getControlEmissionTotalByFacilityId($facilityId, $planNumber)
    {
        $company = new CompanyService();
        $type    = $company->getTypeByFacilityId($facilityId);
        $result  = '';
        //脱硝
        if ($type == 1) {
            $nitre  = new NitreEmissionService();
            $result = $nitre->beforeSingleCompanySingleDrainSingleFacilityTotal($facilityId, $planNumber);
        }
        //脱硫
        if ($type == 2) {
            $sulfur = new SulfurEmissionService();
            $result = $sulfur->beforeSingleCompanySingleDrainSingleFacilityTotal($facilityId, $planNumber);
        }
        return $result;
    }

    /**
     * 获取单个排口的排放量 - 小时平均值
     * @param int $drainId 排口ID
     * @param string $planNumber 预案编号
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-25
     */
    public function getSingleDrainEmissionsHourAvg($drainId, $planNumber)
    {
        $company           = new CompanyService();
        $isRealtimeCompany = $company->isRealtimeCompanyByDrainId($drainId);
        $totalEmission     = [];
        if ($isRealtimeCompany == 1) {
            //脱硫排放量
            $sulfur         = new SulfurEmissionService();
            $sulfurEmission = $sulfur->beforeSingleCompanySingleDrainHourAverage($drainId, $planNumber);
            $sulfurEmission = round($sulfurEmission, 2);
            //脱硝排放量
            $nitre         = new NitreEmissionService();
            $nitreEmission = $nitre->beforeSingleCompanySingleDrainHourAverage($drainId, $planNumber);
            $nitreEmission = round($nitreEmission, 2);
            //排放总量
            $totalEmission['drain_id']      = $drainId;
            $totalEmission['so2_emissions'] = $sulfurEmission;
            $totalEmission['nox_emissions'] = $nitreEmission;
        }
        if ($isRealtimeCompany == 0) {
            $simulation    = new SimulationEmissionService();
            $totalEmission = $simulation->getSimulationSingleCompanySingleDrainEmissionHourAvg($drainId);
        }
        return $totalEmission;
    }

    /**
     * 获取单个排口中的排放量 - 天平均值
     * @param int $drainId 排口ID
     * @param string $planNumber 预案编号
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-25
     */
    public function getSingleDrainEmissionsDayAvg($drainId, $planNumber)
    {
        $company           = new CompanyService();
        $isRealtimeCompany = $company->isRealtimeCompanyByDrainId($drainId);
        $totalEmission     = [];
        if ($isRealtimeCompany == 1) {
            //脱硫排放量
            $sulfur         = new SulfurEmissionService();
            $sulfurEmission = $sulfur->beforeSingleCompanySingleDrainDayAverage($drainId, $planNumber);
            $sulfurEmission = round($sulfurEmission, 2);
            //脱硝排放量
            $nitre         = new NitreEmissionService();
            $nitreEmission = $nitre->beforeSingleCompanySingleDrainDayAverage($drainId, $planNumber);
            $nitreEmission = round($nitreEmission, 2);
            //排放总量
            $totalEmission['drain_id']      = $drainId;
            $totalEmission['so2_emissions'] = $sulfurEmission;
            $totalEmission['nox_emissions'] = $nitreEmission;
        }
        if ($isRealtimeCompany == 0) {
            $simulation    = new SimulationEmissionService();
            $totalEmission = $simulation->getSimulationSingleCompanySingleDrainEmissionHourAvg($drainId);
        }
        return $totalEmission;
    }

    /**
     * 获取单个排口排放量 - 每个小时总量详情
     * @param $drainId
     * @param $planNumber
     * @param string $type before减排前|control管控期间|plan方案值
     * @return array
     * @@throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-25
     */
    public function getSingleDrainEmissionDetailsEveryHour($drainId, $planNumber, $type = 'before', $tsinghuaPlanName = false)
    {
        $company           = new CompanyService();
        $isRealtimeCompany = $company->isRealtimeCompanyByDrainId($drainId);
        //获取企业小时时间
        $control         = new ControlService();
        $everyHoursArray = [];
        if ($type == 'before') {
            $everyHoursArray = $control->getBeforeEveryHours($planNumber);
        }
        if ($type == 'plan') {
            $everyHoursArray = $control->getBeforeEveryHours($planNumber);
        }
        if ($type == 'control') {
            $everyHoursArrayTemp = $control->getControlValidEveryHour($planNumber);
            $everyHoursArray     = [];
            foreach ($everyHoursArrayTemp as $ke => $ve) {
                array_push($everyHoursArray, $ve['publish_time']);
            }
        }
        //实时企业
        $newData     = [];
        $newDataLast = [];
        if ($isRealtimeCompany == 1 && $type != 'plan') {
            $sulfur         = new SulfurEmissionService();
            $nitre          = new NitreEmissionService();
            $sulfurEmission = [];
            $nitreEmission  = [];
            if ($type == 'before') {
                $sulfurEmission = $sulfur->beforeSingleCompanySingleDrainEveryHour($drainId, $planNumber); //脱硫排放量
                $nitreEmission  = $nitre->beforeSingleCompanySingleDrainEveryHour($drainId, $planNumber);  //脱硝排放量
            }
            if ($type == 'control') {
                $sulfurEmission = $sulfur->controlSingleCompanySingleDrainEveryHour($drainId, $planNumber); //脱硫排放量
                $nitreEmission  = $nitre->controlSingleCompanySingleDrainEveryHour($drainId, $planNumber);  //脱硝排放量
            }

            if (empty($sulfurEmission)) {
                return false;
            }
            if (empty($nitreEmission)) {
                return false;
            }
            //每小时排放量
            foreach ($sulfurEmission as $k => $v) {
                foreach ($nitreEmission as $k2 => $v2) {
                    if ($v['time'] == $v2['time']) {
                        $newData[$k]['drain_id']      = $drainId;
                        $newData[$k]['publish_time']  = $v['time'];
                        $newData[$k]['so2_emissions'] = $v['so2_emission'];
                        $newData[$k]['nox_emissions'] = $v2['no2_emission'];
                    }
                }
            }
            $newDataLast = [];
            //根据时间进行判断
            foreach ($everyHoursArray as $k3 => $v3) {
                $newDataLast[$k3]['drain_id']      = $drainId;
                $newDataLast[$k3]['publish_time']  = $v3;
                $newDataLast[$k3]['so2_emissions'] = 0;
                $newDataLast[$k3]['nox_emissions'] = 0;
                foreach ($newData as $k4 => $v4) {
                    if (substr($v3, 0, 13) == $v4['publish_time']) {
                        $newDataLast[$k3]['so2_emissions'] = $v4['so2_emissions'];
                        $newDataLast[$k3]['nox_emissions'] = $v4['nox_emissions'];
                    }
                }
            }
        }
        //模拟企业
        if ($isRealtimeCompany == 0 && $type != 'plan') {
            $simulation = new SimulationEmissionService();
            $emission   = $simulation->getSimulationSingleCompanySingleDrainEmissionHourAvg($drainId);
            foreach ($everyHoursArray as $k5 => $v5) {
                $newDataLast[$k5]['drain_id']      = $drainId;
                $newDataLast[$k5]['publish_time']  = $v5;
                $newDataLast[$k5]['so2_emissions'] = $emission['so2_emissions'];
                $newDataLast[$k5]['nox_emissions'] = $emission['nox_emissions'];
            }
        }
        //计算清华方案值
        if ($type == 'plan') {
            $tsinghua       = new TsinghuaEmissionService();
            $sulfurEmission = $tsinghua->getTsinghuaSingleCompanySingleDrainEmission('so2', 1, $planNumber, $drainId, $tsinghuaPlanName, 'mg', 'hour');
            $nitreEmission  = $tsinghua->getTsinghuaSingleCompanySingleDrainEmission('no2', 1, $planNumber, $drainId, $tsinghuaPlanName, 'mg', 'hour');
            if (empty($sulfurEmission)) {
                return false;
            }
            if (empty($nitreEmission)) {
                return false;
            }
            //每小时排放量
            foreach ($sulfurEmission as $k => $v) {
                foreach ($nitreEmission as $k2 => $v2) {
                    $newData[$k]['drain_id']      = $drainId;
                    $newData[$k]['publish_time']  = $v['time'];
                    $newData[$k]['so2_emissions'] = $v['so2_emission'];
                    if ($v['time'] == $v2['time']) {
                        $newData[$k]['nox_emissions'] = $v2['no2_emission'];
                    }
                }
            }
            $newDataLast = [];
            //根据时间进行判断
            foreach ($everyHoursArray as $k3 => $v3) {
                $newDataLast[$k3]['drain_id']      = $drainId;
                $newDataLast[$k3]['publish_time']  = $v3;
                $newDataLast[$k3]['so2_emissions'] = 0;
                $newDataLast[$k3]['nox_emissions'] = 0;
                foreach ($newData as $k4 => $v4) {
                    if (substr($v3, 0, 13) == $v4['publish_time']) {
                        $newDataLast[$k3]['so2_emissions'] = $v4['so2_emissions'];
                        $newDataLast[$k3]['nox_emissions'] = $v4['nox_emissions'];
                    }
                }
            }
        }
        return $newDataLast;
    }


    /**
     * 获取单个排口排放量 - 每个小时总量详情
     * @param $drainId
     * @param $planNumber
     * @param string $type before减排前|control管控期间|plan方案值
     * @param string $tsinghuaPlanName 方案1|方案2|方案3
     * @return array
     * @@throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-08-13
     */
    public function getSingleDrainEmissionDetailsHourAvg($drainId, $planNumber, $type = 'before', $tsinghuaPlanName = '方案1')
    {
        $company           = new CompanyService();
        $isRealtimeCompany = $company->isRealtimeCompanyByDrainId($drainId);
        //step1:实时企业
        $newData = [];
        if ($isRealtimeCompany == 1 && $type != 'plan') {
            $sulfur = new SulfurEmissionService();
            $nitre  = new NitreEmissionService();
            if ($type == 'before') {
                $sulfurEmission           = $sulfur->beforeSingleCompanySingleDrainHourAvg($drainId, $planNumber); //脱硫排放量
                $nitreEmission            = $nitre->beforeSingleCompanySingleDrainHourAvg($drainId, $planNumber);  //脱硝排放量
                $newData['drain_id']      = $drainId;
                $newData['so2_emissions'] = $sulfurEmission;
                $newData['nox_emissions'] = $nitreEmission;
            }
            if ($type == 'control') {
                $sulfurEmission           = $sulfur->controlSingleCompanySingleDrainHourAvg($drainId, $planNumber); //脱硫排放量
                $nitreEmission            = $nitre->controlSingleCompanySingleDrainHourAvg($drainId, $planNumber);  //脱硝排放量
                $newData['drain_id']      = $drainId;
                $newData['so2_emissions'] = $sulfurEmission;
                $newData['nox_emissions'] = $nitreEmission;
            }
        }
        //step2:模拟企业
        if ($isRealtimeCompany == 0 && $type != 'plan') {
            $simulation = new SimulationEmissionService();
            $newData    = $simulation->getSimulationSingleCompanySingleDrainEmissionHourAvg($drainId);
        }
        //step3:计算清华方案值
        if ($type == 'plan') {
            $tsinghua                 = new TsinghuaEmissionService();
            $sulfurEmission           = $tsinghua->getTsinghuaSingleCompanySingleDrainEmission('so2', 1, $planNumber, $drainId, $tsinghuaPlanName);
            $nitreEmission            = $tsinghua->getTsinghuaSingleCompanySingleDrainEmission('no2', 1, $planNumber, $drainId, $tsinghuaPlanName);
            $newData['drain_id']      = $drainId;
            $newData['so2_emissions'] = $sulfurEmission['tsinghua_emission'] * 1000000; //转换为mg
            $newData['nox_emissions'] = $nitreEmission['tsinghua_emission'] * 1000000; //转换为mg
        }
        return $newData;
    }


    /**
     * 获取单个排口排放量 - 每个小时总量详情
     * @param $drainId
     * @param $planNumber
     * @param string $type before减排前|control管控期间
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-25
     */
    public function getSingleDrainEmissionDetailsEveryDay($drainId, $planNumber, $type = 'before')
    {
        $company           = new CompanyService();
        $isRealtimeCompany = $company->isRealtimeCompanyByDrainId($drainId);
        //获取企业天时间
        $control        = new ControlService();
        $everyDaysArray = $control->getBeforeEveryDays($planNumber);
        //实时企业
        $newData     = [];
        $newDataLast = [];
        if ($isRealtimeCompany == 1) {
            $sulfur         = new SulfurEmissionService();
            $nitre          = new NitreEmissionService();
            $sulfurEmission = [];
            $nitreEmission  = [];
            if ($type == 'before') {
                $sulfurEmission = $sulfur->beforeSingleCompanySingleDrainEveryDay($drainId, $planNumber);  //脱硫排放量
                $nitreEmission  = $nitre->beforeSingleCompanySingleDrainEveryDay($drainId, $planNumber); //脱硝排放量
            }
            if ($type == 'control') {
                $sulfurEmission = $sulfur->controlSingleCompanySingleDrainEveryDay($drainId, $planNumber);  //脱硫排放量
                $nitreEmission  = $nitre->controlSingleCompanySingleDrainEveryDay($drainId, $planNumber); //脱硝排放量
            }
            //每小时排放量
            foreach ($sulfurEmission as $k => $v) {
                foreach ($nitreEmission as $k2 => $v2) {
                    if ($v['time'] == $v2['time']) {
                        $newData[$k]['drain_id']      = $drainId;
                        $newData[$k]['publish_time']  = $v['time'];
                        $newData[$k]['so2_emissions'] = $v['so2_emission'];
                        $newData[$k]['nox_emissions'] = $v2['no2_emission'];
                    }
                }
            }
            $newDataLast = $newData;
            //根据时间进行判断
            foreach ($everyDaysArray as $k3 => $v3) {
                $newDataLast[$k3]['drain_id']      = $drainId;
                $newDataLast[$k3]['publish_time']  = $v3;
                $newDataLast[$k3]['so2_emissions'] = 0;
                $newDataLast[$k3]['nox_emissions'] = 0;
                foreach ($newData as $k4 => $v4) {
                    if (substr($v3, 0, 13) == $v4['publish_time']) {
                        $newDataLast[$k3]['so2_emissions'] = $v4['so2_emissions'];
                        $newDataLast[$k3]['nox_emissions'] = $v4['nox_emissions'];
                    }
                }
            }
        }
        //模拟企业
        if ($isRealtimeCompany == 0) {
            $simulation = new SimulationEmissionService();
            $emission   = $simulation->getSimulationSingleCompanySingleDrainEmissionDayAvg($drainId);
            foreach ($everyDaysArray as $k5 => $v5) {
                $newDataLast[$k5]['drain_id']      = $drainId;
                $newDataLast[$k5]['so2_emissions'] = $emission['so2_emissions'];
                $newDataLast[$k5]['nox_emissions'] = $emission['nox_emissions'];
            }
        }
        return $newDataLast;
    }

    /**
     * 单个企业的总排放量
     * @param int $companyId 公司ID
     * @param string $planNumber 预案编号
     * @param string $type 污染物类型
     * @return array|float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-26
     */
    public function controlSingleCompanyTotalEmission($companyId, $planNumber, $type = 'so2')
    {
        //step1:根据企业ID判断是实时企业还是模拟企业
        $company       = new CompanyService();
        $realtime      = $company->isRealtimeCompany($companyId);
        $totalEmission = 0;
        //step2:如果是实时企业，到实时排放量相关污染物
        if ($realtime == 1 && strtoupper($type) == 'SO2') {
            $sulfur        = new SulfurEmissionService();
            $totalEmission = $sulfur->beforeSingleCompanyTotal($companyId, $planNumber);
        }
        if ($realtime == 1 && strtoupper($type) == 'NO2') {
            $nitre         = new NitreEmissionService();
            $totalEmission = $nitre->beforeSingleCompanyTotal($companyId, $planNumber);
        }
        //step3:如果是模拟企业，到模拟排放量相关污染物s
        if ($realtime == 0) {
            $simulation    = new SimulationEmissionService();
            $control       = new ControlService();
            $days          = $control->getBeforeDays();
            $totalEmission = $simulation->getSimulationEmissionWayOne($days, $companyId, $type);
        }
        return $totalEmission;
    }

    /**
     * 获取排口减排量（清华排放量和减排前排放量）
     * @param string $planNumber 预案编号
     * @param string $type 污染物类型
     * @param string $tsinghuaPlanName 清华方案
     * @author hongwei 2019-08-02
     */
    public function getReductionEmission($planNumber, $type = 'SO2', $tsinghuaPlanName = '方案1')
    {
        //step1:获取管控排口清单
        $control         = new ControlService();
        $controlDrainIds = $control->getControlListDrainsIds($planNumber);

        //step2:获取实时排口
        $company      = new CompanyService();
        $realDrainIds = $company->getRealtimeDrainIds();

        //step3:排口清单中区分实时排口 和 模拟排口
        $controlDrainIdsArr        = explode(',', $controlDrainIds);
        $realDrainIdsArr           = explode(',', $realDrainIds);
        $controlRealDrainIdsArr    = array_intersect($controlDrainIdsArr, $realDrainIdsArr); //交集
        $controlMonitorDrainIdsArr = array_diff($controlDrainIdsArr, $realDrainIdsArr); //差集


        $dataReal    = [];
        $dataMonitor = [];
        //step4:实时排口查询（减排前）和（方案值）
        $tsinghua = new TsinghuaEmissionService();
        if ($controlRealDrainIdsArr) {
            $controlRealDrainIds = implode(",", $controlRealDrainIdsArr);

            //方案值
            $resultRealTsinghua = $tsinghua->getTsinghuaControlDrainIdsEmissionType($type, $controlRealDrainIds, $planNumber, $tsinghuaPlanName, 'mg');

            //整合并区分污染物
            $dataReal[$realDrainIds]['type']           = $type; //减排前
            $dataReal[$realDrainIds]['drain_id']       = $realDrainIds; //排口ID
            $dataReal[$realDrainIds]['plan_emissions'] = $resultRealTsinghua[$realDrainIds]['tsinghua_emission']; //方案值
            if (strtoupper($type) == 'SO2') {
                //脱硫排放量
                $sulfur         = new SulfurEmissionService();
                $sulfurEmission = $sulfur->beforeSingleCompanySingleDrainHourAverage($realDrainIds, $planNumber);
                $sulfurEmission = round($sulfurEmission, 2);

                $dataReal[$realDrainIds]['before_emissions']    = $sulfurEmission; //减排前
                $dataReal[$realDrainIds]['reduction_emissions'] = (float)$sulfurEmission - (float)$resultRealTsinghua[$realDrainIds]['tsinghua_emission']; //减排量
            }

            if (strtoupper($type) == 'NO2') {
                //脱硝排放量
                $nitre         = new NitreEmissionService();
                $nitreEmission = $nitre->beforeSingleCompanySingleDrainHourAverage($realDrainIds, $planNumber);
                $nitreEmission = round($nitreEmission, 2);

                $dataReal[$realDrainIds]['before_emissions']    = $nitreEmission; //减排前
                $dataReal[$realDrainIds]['reduction_emissions'] = (float)$nitreEmission - (float)$resultRealTsinghua[$realDrainIds]['tsinghua_emission']; //减排量
            }
            $dataReal = array_values($dataReal);
        }

        //step5:模拟排口查询（减排前）和（方案值）
        if ($controlMonitorDrainIdsArr) {
            $controlMonitorDrainIds = implode(",", $controlMonitorDrainIdsArr);
            //减排前
            $simulation       = new SimulationEmissionService();
            $resultSimulation = $simulation->getSimulationControlDrainIdsEmissionTypeHourAvg($controlMonitorDrainIds, $type, 'mg');

            //方案值
            $resultSimulationTsinghua = $tsinghua->getTsinghuaControlDrainIdsEmissionType($type, $controlMonitorDrainIds, $planNumber, $tsinghuaPlanName, 'mg');

            //整合并区分污染物
            $dataMonitor = [];
            foreach ($resultSimulation as $k => $v) {
                $dataMonitor[$k]['type']             = $type;
                $dataMonitor[$k]['drain_id']         = $v['drain_id'];
                $dataMonitor[$k]['before_emissions'] = $v['emissions'];
                foreach ($resultSimulationTsinghua as $k2 => $v2) {
                    if ($v['drain_id'] == $v2['drain_id']) {
                        $dataMonitor[$k]['plan_emissions']      = $v2['tsinghua_emission']; //方案值
                        $dataMonitor[$k]['reduction_emissions'] = (float)$v['emissions'] - (float)$v2['tsinghua_emission']; //减排量
                    }
                }
            }
        }

        //step6:整合实时和模拟数据
        $lastData = array_merge($dataReal, $dataMonitor);


        return $lastData;
    }

    /**
     * 单个行业的总排放量
     * @param int $industryId 行业ID
     * @param string $playNumber 预案编号
     * @param string $type 污染物类型
     * @return array|float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-26
     */
    public function controlSingleIndustryTotalEmission($industryId, $playNumber, $type = 'so2')
    {
        //step1:实时企业排放量
        if (strtoupper($type) == 'SO2') {
            $sulfur            = new SulfurEmissionService();
            $realTotalEmission = $sulfur->beforeSingleIndustryTotal($industryId, $playNumber);
        }
        if (strtoupper($type) == 'NO2') {
            $nitre             = new NitreEmissionService();
            $realTotalEmission = $nitre->beforeSingleIndustryTotal($industryId, $playNumber);
        }
        $realTotalEmission = isset($realTotalEmission) ? $realTotalEmission : 0;

        //step2:模拟企业排放量
        $control                    = new ControlService();
        $days                       = $control->getBeforeDays();
        $simulation                 = new SimulationEmissionService();
        $simulationTotalEmissionArr = [];
        if (strtoupper($type) == 'SO2') {
            $simulationTotalEmissionArr = $simulation->getSimulationSingleIndustryEmissionHourAvg($industryId, 'SO2');
        }
        if (strtoupper($type) == 'NO2') {
            $simulationTotalEmissionArr = $simulation->getSimulationSingleIndustryEmissionHourAvg($industryId, 'NO2');
        }
        $simulationTotalEmission = $simulationTotalEmissionArr['emissions'];
        $simulationTotalEmission = isset($simulationTotalEmission) ? $simulationTotalEmission : 0;
        $simulationTotalEmission = $simulationTotalEmission * $days * 24; //转换7天的

        //step3:两者排放量相加
        $totalEmission = $realTotalEmission + $simulationTotalEmission;
        return $totalEmission;
    }

    /**
     * 单个行业的总排放量
     * @param int $industryId 行业ID
     * @param string $playNumber 预案编号
     * @param string $type 污染物类型
     * @return array|float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-26
     */
    public function controlEveryIndustryTotalEmission($playNumber)
    {
        //step1:实时企业排放量
        $realEmission      = new RealtimeEmissionService();
        $realTotalEmission = $realEmission->everyIndustry($playNumber);

        //step2:模拟企业排放量
        $control                    = new ControlService();
        $days                       = $control->getBeforeDays();
        $simulation                 = new SimulationEmissionService();
        $simulationTotalEmissionArr = $simulation->getSimulationEveryIndustryEmissionHourAvg();
        $simulationTotalEmissionNew = [];
        foreach ($simulationTotalEmissionArr as $k => $v) {
            $simulationTotalEmissionNew[$k]['industry_id']   = (int)$v['industry_id'];
            $simulationTotalEmissionNew[$k]['so2_emissions'] = $v['so2_emissions'] * $days * 24; //转换7天的
            $simulationTotalEmissionNew[$k]['no2_emissions'] = $v['no2_emissions'] * $days * 24; //转换7天的
        }

        //step3:两者排放量相加
        $newData = array_merge($realTotalEmission, $simulationTotalEmissionNew);

        $result = [];
        //二维数据根据相同的industry_id进行求和
        array_walk($newData, function ($item) use (&$result) {
            $industryId = $item['industry_id'];
            if (isset($result[$industryId])) {
                $tmp                  = $result[$industryId];
                $tmp['so2_emissions'] = bcadd($tmp['so2_emissions'], $item['so2_emissions'], 2);
                $tmp['no2_emissions'] = bcadd($tmp['no2_emissions'], $item['no2_emissions'], 2);
                $result[$industryId]  = $tmp;
            } else {
                $result[$industryId] = $item;
            }
        });
        $result = array_values($result);
        return $result;
    }

    /**
     * 获取公司 减排前 和 方案值的排放量
     * @param $type
     * @param $controlModeId
     * @param $planNumber
     * @param $tsinghuaPlanName
     * @param $endDay
     * @param $days
     * @param $unit
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-10
     */
    public function getTsinghuaCompanyEmission($type, $controlModeId, $planNumber, $tsinghuaPlanName, $unit)
    {
        $control = new ControlService();
        $endDay = $control->getBeforeEndTime($planNumber);
        $days = $control->getBeforeDays();
        //step1:清华方案下的排放量
        $tsinghua     = new TsinghuaEmissionService();
        $dataTsinghua = $tsinghua->getTsinghuaAllCompanyDrainEmissionType($type, $controlModeId, $planNumber, $tsinghuaPlanName);

        //step2:获取实时企业的脱硝和脱硫减排量
        $sulfur     = new SulfurEmissionService();
        $nitre      = new NitreEmissionService();
        $simulation = new SimulationEmissionService();
        //脱硫
        $realTimeCompanySulfurEmission = $sulfur->getRealtimeAllCompanyDrainEmissionSulfurMinToHourAvg($endDay, $days, $unit);
        //脱硝
        $realTimeCompanyNitreEmission = $nitre->getRealtimeAllCompanyDrainEmissionNitreMinToHourAvg($endDay, $days, $unit);

        //step4:获取模拟企业的脱硝和脱硫减排量
        $simulationCompanyEmission = $simulation->getSimulationAllCompanyDrainEmissionHourAvg($unit);

        //step5:实时企业整合
        $companyEmission = [];
        foreach ($realTimeCompanySulfurEmission as $k2 => $v2) {
            foreach ($realTimeCompanyNitreEmission as $k3 => $v3) {
                if ($v2['drain_id'] == $v3['drain_id']) {
                    $companyEmission[$k2]['company_id']    = $v2['company_id'];
                    $companyEmission[$k2]['drain_id']      = $v2['drain_id'];
                    $companyEmission[$k2]['drain_name']    = $v2['drain_name'];
                    $companyEmission[$k2]['nox_emissions'] = $v3['nox_emissions'];
                    $companyEmission[$k2]['so2_emissions'] = $v2['so2_emissions'];
                    $companyEmission[$k2]['tsp_emissions'] = $v2['tsp_emissions'];
                }
            }
        }
        $companyEmission = field_as_key($companyEmission, 'company_id');

        //step6：实时企业和模拟企业整合
        foreach ($simulationCompanyEmission as $k4 => $v4) {
            $companyEmission[$k4]['company_id']    = $v4['company_id'];
            $companyEmission[$k4]['drain_id']      = $v4['drain_id'];
            $companyEmission[$k4]['drain_name']    = $v4['drain_name'];
            $companyEmission[$k4]['so2_emissions'] = $v4['so2_emissions'];
            $companyEmission[$k4]['nox_emissions'] = $v4['nox_emissions'];
            $companyEmission[$k4]['tsp_emissions'] = $v4['tsp_emissions'];
        }

        //step7:清华排放量 和 实时企业模拟企业 整合
        $lastEmission = [];
        foreach ($dataTsinghua as $k5 => $v5) {
            //基本信息
            $lastEmission[$k5]['control_mode_id']    = $controlModeId;    //管控方式ID,1工业减排
            $lastEmission[$k5]['plan_number']        = $planNumber;       //预案编号
            $lastEmission[$k5]['tsinghua_plan_name'] = $tsinghuaPlanName; //预案编号对应的清华方案名称

            foreach ($companyEmission as $k6 => $v6) {
                if ((int)$k5 == (int)$k6) { //如果排口相同

                    //相关ID
                    $lastEmission[$k5]['company_id']   = $v6['company_id'];     //公司ID
                    $lastEmission[$k5]['company_name'] = $v5['company_name'];   //公司名称
                    $lastEmission[$k5]['drain_id']     = $v6['drain_id'];       //排口ID号
                    $lastEmission[$k5]['drain_name']   = $v6['drain_name'];     //排口编号

                    //排放量
                    $formula = new FormulaService();
                    if (strtoupper($type) == 'SO2') {
                        $lastEmission[$k5]['origin_emissions']   = $v6['so2_emissions'];  //原始：SO2排放量
                        $lastEmission[$k5]['tsinghua_emissions'] = $v5['tsinghua_emission']; //清华方案：SO2排放量
                        $lastEmission[$k5]['target_emissions']   = $formula->targetEmission($v6['so2_emissions'], $v5['tsinghua_emission']); //目标减排量
                    }
                    if (strtoupper($type) == 'NO2') {
                        $lastEmission[$k5]['origin_emissions']   = $v6['nox_emissions'];  //原始：NOX排放量
                        $lastEmission[$k5]['tsinghua_emissions'] = $v5['tsinghua_emission']; //清华方案：NOX排放量
                        $lastEmission[$k5]['target_emissions']   = $formula->targetEmission($v6['nox_emissions'], $v5['tsinghua_emission']); //目标减排量
                    }
                    $lastEmission[$k5]['type']           = $type; //类型
                    $lastEmission[$k5]['emissions_unit'] = $unit; //单位
                }
            }
        }
        $lastEmission = array_values($lastEmission);
        return $lastEmission;
    }

    /**
     * 得到管控时段内公司所有的排放量总和
     * @param $planNumber
     * @param string $emissionUnit
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-16
     */
    public function getTsinghuaTimesOriginCompanyEmissionTotalCompanyHourAvg($planNumber, $emissionUnit = 'kg')
    {
        try {
            //step1:获取管控开始和结束时间
            $control             = new ControlService();
            $controlBeforeEndDay = $control->getBeforeEndTime($planNumber);
            $controlBeforeDays   = $control->getBeforeDays();

            //step2:获取管控对应的清华方案公司ID
            $tsinghua       = new TsinghuaEmissionService();
            $companyIds     = $tsinghua->getTsinghuaPlanCompanyIds($planNumber);
            $newEmissionArr = [];
            $emission       = new EmissionService();
            foreach ($companyIds as $k => $v) {
                $newEmissionArr[$k] = $emission->getSingleCompanyEmissionMinToHourAvg((int)$v, $controlBeforeEndDay, $controlBeforeDays, $emissionUnit);
            }

            //step3:获取小时数的总量
            $newEmissionArr2 = [];
            foreach ($newEmissionArr as $k2 => $v2) {
                $newEmissionArr2[$k2]['company_id']    = $v2['company_id'];
                $newEmissionArr2[$k2]['company_name']  = $v2['company_name'];
                $newEmissionArr2[$k2]['so2_emissions'] = isset($v2['so2_emissions_supplement']) ? $v2['so2_emissions_supplement'] : $v2['so2_emissions'];
                $newEmissionArr2[$k2]['no2_emissions'] = isset($v2['nox_emissions_supplement']) ? $v2['nox_emissions_supplement'] : $v2['nox_emissions'];
                $newEmissionArr2[$k2]['tsp_emissions'] = isset($v2['tsp_emissions_supplement']) ? $v2['tsp_emissions_supplement'] : $v2['tsp_emissions'];
            }

            //step4:新数组排放量并进行求和
            $newSo2Emission = [];
            $newNoxEmission = [];
            $newTspEmission = [];
            foreach ($newEmissionArr2 as $k3 => $v3) {
                array_push($newSo2Emission, $v3['so2_emissions']);
                array_push($newNoxEmission, $v3['no2_emissions']);
                array_push($newTspEmission, $v3['tsp_emissions']);
            }

            //step4:对所有数据进行排放量求和
            $emissionTotal                  = [];
            $emissionTotal['so2_emissions'] = array_sum($newSo2Emission);
            $emissionTotal['no2_emissions'] = array_sum($newNoxEmission);
            $emissionTotal['tsp_emissions'] = array_sum($newTspEmission);
            $emissionTotal['unit']          = $emissionUnit;

            return $emissionTotal;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }


    /**
     * 管控中减排完成率
     * @param $drainId
     * @param $planNumber
     * @param $tsinghuaPlanName
     * @param $pollutantType
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-08-14
     */
    public function getSingleDrainEmissionCompletionRate($drainId, $planNumber, $tsinghuaPlanName, $pollutantType = 'SO2')
    {
        $achieveReduceTotal = $this->getSingleDrainEmissionDetailsHourAvg($drainId, $planNumber, 'control', $tsinghuaPlanName);
        $planReduceTotal    = $this->getSingleDrainEmissionDetailsHourAvg($drainId, $planNumber, 'plan', $tsinghuaPlanName);
        $formula            = new FormulaService();
        $result['drain_id'] = $drainId;
        if (strtoupper($pollutantType) == 'SO2') {
            $result['target_emission']  = $planReduceTotal['so2_emissions'];
            $result['archive_emission'] = $achieveReduceTotal['so2_emissions'];
            $result['rate_emission']    = $formula->getPlanReduceAchieveRate($achieveReduceTotal['so2_emissions'], $planReduceTotal['so2_emissions']);
        }
        if (strtoupper($pollutantType) == 'NO2') {
            $result['target_emission']  = $planReduceTotal['nox_emissions'];
            $result['archive_emission'] = $achieveReduceTotal['nox_emissions'];
            $result['rate_emission']    = $formula->getPlanReduceAchieveRate($achieveReduceTotal['nox_emissions'], $planReduceTotal['nox_emissions']);
        }
        return $result;
    }

}